"""
sem = Semaphore(n) => 运行N个线程同时访问
sem.acquire() # 获取信号量
sem.release() # 释放信号量
"""
import time
import threading
# 创建运行2个线程同时访问的信号量
sem = threading.Semaphore(2)
def print_task(task_name):
    with sem: # 自动的获取和释放信号量
        print(f"{task_name}开始打印...")
        time.sleep(2)
        print(f"{task_name}打印结束")
if __name__ == '__main__':
    # 创建5个人
    tasks = ["数学作业","语文作业","英语作业","科学作业","历史作业"]
    threads = []
    for task in tasks:
        t = threading.Thread(target=print_task,args=(task,))
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
    print("所有打印任务完成")